﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IRIS.Models;
using System.Web.Security;

namespace IRIS.Controllers
{
    [HandleError]
    public class ContentController : Controller
    {
        DataRepo m_Db = new DataRepo();

        #region Index Details & Groups GetMethods
        
        [HttpGet]
        public ActionResult Index()
        {
            //Count how many pages there are
            var Pages = m_Db.getArticles().Count() / 5.0;
            Pages = Math.Ceiling(Pages);
            int intPages = Convert.ToInt32(Pages);
            IEContentIECategoriesViewModel cData = new IEContentIECategoriesViewModel
                                      { m_Contents = m_Db.getArticles().Take(5), m_Categories = m_Db.getContentCategories(), m_Pages = intPages};

            return View(cData);
        }

        public ActionResult Page(int? thePage, Boolean theNews)
        {
            try
            {
                if (!thePage.HasValue)
                {
                    throw new Exception("Engin blaðsíða valin");
                }
                //Skips 5 content times the page value and takes 5
                if (theNews == true)
                {
                    var News = m_Db.getNews().Skip(5 * thePage.Value).Take(5);
                    //Count how many pages there are
                    var Pages = m_Db.getNews().Count() / 5.0;
                    Pages = Math.Ceiling(Pages);
                    int intPages = Convert.ToInt32(Pages);
                    IEContentIECategoriesIntPagesViewModel cData = new IEContentIECategoriesIntPagesViewModel { m_Contents = News, m_Categories = m_Db.getContentCategories(), m_Pages = intPages };
                    return View(cData);
                }
                else
                {
                    var Articles = m_Db.getArticles().Skip(5 * thePage.Value).Take(5);
                    //Count how many pages there are
                    var Pages = m_Db.getArticles().Count() / 5.0;
                    Pages = Math.Ceiling(Pages);
                    int intPages = Convert.ToInt32(Pages);
                    IEContentIECategoriesIntPagesViewModel cData = new IEContentIECategoriesIntPagesViewModel { m_Contents = Articles, m_Categories = m_Db.getContentCategories(), m_Pages = intPages };
                    return View(cData);
                }

            }
            catch (Exception e)
            {
                
                throw e;
            }
        }
        [HttpGet]
        public ActionResult List(bool news)
        {
            IEnumerable<Content> model;
            if(news == true)
            {
                model = m_Db.getNews();
                return View(model);   
            }
            model = m_Db.getArticles();
            return View(model);
        }
        //Takes in id of Content and returns in Details View
        [HttpGet]
        public ActionResult Details(int? id)
        {
            if(id.HasValue)
            {
                int realId = id.Value;
               
                if (m_Db.getArticleToApproveById(realId) != null)
                {
                    ContentIECategoriesViewModel cData = new ContentIECategoriesViewModel { m_Content = m_Db.getArticleToApproveById(realId), m_Categories = m_Db.getContentCategories() };
                    return View(cData);
                }
                else 
                {
                    ContentIECategoriesViewModel cData = new ContentIECategoriesViewModel { m_Content = m_Db.getContentById(realId), m_Categories = m_Db.getContentCategories() };
                
                    if(cData.m_Content != null)
                    {
                        return View(cData);
                    }
                }
            }
            return View("NotFound");   
        }
       
        [HttpGet]
        public ActionResult Groups(int? id)
        {
            if (id.HasValue)
            {
                IEContentsIECategoriesCategoryViewModel cData = new IEContentsIECategoriesCategoryViewModel 
                            { m_Contents = m_Db.getArticleByCategoryId(id), m_ContentCategory = m_Db.getContentCategoryById(id), m_Categories = m_Db.getContentCategories()};
                if (cData != null)
                {
                    return View(cData);
                }  
            }
            return View("NotFound");
        }
        #endregion
        #region Edit
        //Gets an article byID and returns the data in view. 
        //Edit is also used to delete article where alive is edited to false
        [Authorize(Roles = "Stjórnendur")]
        [HttpGet]
        public ActionResult Edit(int? id, Boolean delete)
        {
            if (id.HasValue)
            {
                int realId = id.Value;
                ContentIECategoriesViewModel cData = new ContentIECategoriesViewModel { m_Content = m_Db.getContentById(realId), m_Categories = m_Db.getContentCategories() };
                if(cData != null && delete == true)
                {
                    cData.m_Content.Alive = false;
                    m_Db.editContent(id.Value, cData.m_Content);
                    if (cData.m_Content.News == true)
                    {
                        return RedirectToAction("List", new { news = true });
                    }
                    return RedirectToAction("List", new { news = false });
                }
                else if (cData != null && delete == false)
                {
                    return View(cData);
                }
            }
            return View("NotFound");
        }
        /* Gets content information from ContentIECategoriesViewModel theData 
        and sends the information to edit() in DataRepo then returns to Index*/
        [ValidateInput(false)]
        [HttpPost]
        [Authorize(Roles = "Stjórnendur")]
        public ActionResult Edit(ContentIECategoriesViewModel theData)
        {
            if(string.IsNullOrEmpty(theData.m_Content.ContentTitle))
                ModelState.AddModelError("m_Content.ContentTitle", "Titil má ekki vanta");
            if(theData.m_Content.ContentText == "<br>")
                ModelState.AddModelError("m_Content.ContentText", "Innihald má ekki vanta");
            if(theData.m_Content.News == false && theData.m_Content.Description == "<br>")
                ModelState.AddModelError("m_Content.Description", "Lýsingu má ekki vanta");
            try
            {
                if (ModelState.IsValid)
                {

                    m_Db.editContent(theData.m_Content.ID,theData.m_Content);
          
                    if (theData.m_Content.News == true)
                    {
                        return RedirectToAction("List", new { news = true });
                    }
                    return RedirectToAction("List", new { news = false });   
                }
                else
                {
                    //something is wrong and we return the model back with error state
                    theData.m_Categories = m_Db.getContentCategories();
                    return View(theData);
                }
            }
            catch
            {
                //Something is not o.k so we return error state
                return View("Error");
            }
        }
        #endregion
        #region Create
        [Authorize(Roles = "Fagaðilar")]
        [HttpGet]
        public ActionResult Create(Boolean news)
        {
            ContentCreateViewModel cData = new ContentCreateViewModel {m_Categories = m_Db.getContentCategories() , m_News = news};
            
            return View(cData);
        }
        // Stjórnendur are also Fagadilar
        [Authorize(Roles = "Fagaðilar")] 
        [HttpPost]
        [ValidateInput(false)] 
        public ActionResult  Create(ContentCreateViewModel theData)
        {
            if(string.IsNullOrEmpty(theData.m_Content.ContentTitle))
                ModelState.AddModelError("m_Content.ContentTitle", "Titil má ekki vanta");
            if(theData.m_Content.ContentText == "<br>")
                ModelState.AddModelError("m_Content.ContentText", "Innihald má ekki vanta");
            if(theData.m_News == false && theData.m_Content.Description == "<br>")
                ModelState.AddModelError("m_Content.Description", "Lýsingu má ekki vanta");
            try
            {
                if (ModelState.IsValid)
                {
                    //everything is alright and we commit to database
                    var cData = new Content();
                    cData.ContentText = theData.m_Content.ContentText;
                    cData.ContentTitle = theData.m_Content.ContentTitle;
                    cData.Created = DateTime.Now;
                    cData.Modified = DateTime.Now;
                    cData.Author = User.Identity.Name;
                    cData.Alive = true;
                    cData.News = theData.m_News;

                    //All articles that Fagadilar submit are tagged not approved until the administrators review them
                    if (User.IsInRole("Stjórnendur"))
                    {
                        cData.Approved = true;
                    }
                    else
                    {
                        cData.Approved = false;
                    }

                    if (cData.News == true)
                    {
                        cData.CID = 8;
                        cData.Description = " ";
                        UpdateModel(cData);
                        m_Db.addContent(cData);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        cData.Description = theData.m_Content.Description;
                        cData.CID = theData.m_Content.CID;
                        UpdateModel(cData);
                        m_Db.addContent(cData);
                        return RedirectToAction("Index");
                    }
                }
                else
                {
                    //something is wrong and we return the model back with error state
                    theData.m_Categories = m_Db.getContentCategories();
                    return View(theData);
                }
            }
            catch
            {
                //Something is not o.k so we return error state
                return View(theData);
            }
        }
        #endregion
        #region ApproveArticles
        /*Administrator gets a list of all article that haven´t been approved. he can then check with 
          articles he wants to approve*/
        [Authorize(Roles = "Stjórnendur")]
        [HttpGet]
        public ActionResult ApproveArticle()
        {
            var cData =  m_Db.getArticleToApprove();
            if (cData != null)
            {
                return View(cData);
            }
            return View("NotFound");
        }
        /*Post action when administrator has chosen articles he wants to approve. The articles 
          get checked for approval in the Database*/
        [Authorize(Roles = "Stjórnendur")]
        [HttpPost]
        public ActionResult ApproveArticle(FormCollection formData)
        {
            int i = 0;
            for (;;)
            {
                   string strArticle = formData["articleId|"+i];
                   int Articleid;
                   Int32.TryParse(strArticle, out Articleid);
                   if (!String.IsNullOrEmpty(strArticle))
                   {
                       string strIsApproved = formData["accept|" + strArticle];
                       if (!String.IsNullOrEmpty(strIsApproved))
                       {
                           var Data = m_Db.getContentById(Articleid);
                           Data.Approved = true;
                           m_Db.editContent(Articleid, Data);
                       }
                   }
                   else
                   {
                       break;
                   }

                   i++;
              }
            return RedirectToAction("ApproveArticle");
        }
        #endregion
        #region RetrieveArticles
        //Gets all article that are not alive and doesnt have CID that is dead for the administrator to retrieve
        [Authorize(Roles = "Stjórnendur")]
        [HttpGet]
        public ActionResult RetrieveArticle()
        {
            var cData = m_Db.getDeadArticlesToRetrieve();
            if(cData != null)
            {
                return View(cData);
            }
            return View("NotFound");
        }
        //administratos has checked the article he wants to retrieve and submits to database.
        [Authorize(Roles = "Stjórnendur")]
        [HttpPost]
        public ActionResult RetrieveArticle(FormCollection formData)
        {
            int i = 0;
            for (; ; )
            {
                string strArticle = formData["articleId|" + i];
                int Articleid;
                Int32.TryParse(strArticle, out Articleid);
                if (!String.IsNullOrEmpty(strArticle))
                {
                    string strRetrieve = formData["retrieve|" + strArticle];
                    if (!String.IsNullOrEmpty(strRetrieve))
                    {
                        var cData = m_Db.getDeadArticleById(Articleid);
                        m_Db.editDeadToAlive(cData);
                    }
                }
                else
                {
                    break;
                }

                i++;
            }
            return RedirectToAction("RetrieveArticle");
        }
        #endregion
        #region TopContent
        [ChildActionOnly]
        public ActionResult _TopContent()
        {
            var query = m_Db.getArticles();
            var model = (from c in query
                         orderby c.Modified descending
                         select c).Take(2);

            return PartialView(model);
        }
        #endregion
        #region _ContentMenu
        [ChildActionOnly]
        public ActionResult _ContentMenu()
        {
            var model = m_Db.getFiveNewestArticles();
            return PartialView(model);
        }
        #endregion  
    }
}